<template>
  <div class="top">
    <div class="left">
      <img
        src="../assets/logo.png"
        alt=""
        class="logo"
      >
    </div>
    <div class="center">
      <el-menu

    :default-active="activeIndex"
    @select="selected"
    background-color="#121212"
    text-color="#fff"
    mode="horizontal"
    active-text-color="#fff"
    router
  >
    <el-menu-item
      index="/"
    >发现</el-menu-item>
    <el-menu-item
      index="/MyU"
    >本校</el-menu-item>
    <el-menu-item
      index="/MyClub"
    >我的社团</el-menu-item>
    <el-menu-item
      index="/Self"
    >个人中心</el-menu-item>
    <el-menu-item
      index="/publish"
    >发布</el-menu-item>
  </el-menu>
    </div>
    <div class="right">
      <div
        v-if="user.school === null || user.school === ''||user.school === undefined"
        class="top-a"
        @click="handleJoinSchoolClick"
      >加入校园</div>
      <div
      class="top-a"
      v-if="hasAdminRole()"
      @click="goToManage"
      >
        管理员子系统
      </div>
      <div
        v-if="!user.loggedIn"
        class="top-a"
        @click="goToLogin"
      >
        登录注册
      </div>
      <div
        v-else
        class="user-info"
        @mouseenter="showLogoutButton = true"
        @mouseleave="showLogoutButton = false"
      >
        <img
          :src="user.avatar ? `http://localhost:5000/uploads/${user.avatar}` : '/src/assets/touxiang.png'"
          class="user-avatar"
        />
        <span>{{ user.username }}</span>
        <div
          v-if="showLogoutButton"
          class="logout-button"
          @click="logout"
        >退出登录</div>
      </div>
    </div>
    <ChooseSchoolDialog v-model="goToChooseSchool" />
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router'
import { useStore } from '../stores/userStore'
import axios from 'axios'
import ChooseSchoolDialog from '../components/ChooseSchoolDialog.vue'
import { ElMessage } from 'element-plus'

const store = useStore()
const user = store.user
// 不要直接访问 user.value.roles，因为初始化时可能为空
const route = useRoute()
const router = useRouter()
const showLogoutButton = ref(false) // 控制退出登录按钮的显示
const goToChooseSchool = ref(false)
const activeIndex = ref(route.path); // 初始化为当前路由路径

// 获取当前用户信息的函数
const fetchCurrentUser = async () => {
  const token = localStorage.getItem('token');
  if (!token) return;

  try {
    const response = await axios.get('http://localhost:5000/users/me', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    if (response.data) {
      store.setUser(response.data);
      console.log('获取到的用户信息:', response.data);
      console.log('获取到的用户信息:', response.data.gender);
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

watch(
  () => route.path,
  (newPath) => {
    activeIndex.value = newPath;
  }
);

// 判断用户是否拥有管理员角色
const hasAdminRole = () => {
  if (!user.value || !user.value.roles || !Array.isArray(user.value.roles)) {
    console.log('用户角色不存在或不是数组:', user.value);
    return false;
  }

  console.log('用户角色:', user.value.roles);
  const adminRoles = ['clubAdmin', 'schoolAdmin', 'systemAdmin', 'stystemAdmin'];
  return user.value.roles.some(role => adminRoles.includes(role));
};

// 菜单项被选中时的回调
const selected = (index) => {
  console.log(index);
};

function goToLogin () {
  router.push('/login')
}

function goToManage () {
  router.push('/manage')
}

function logout () {
  store.logout(); // 调用 store 中的 logout 方法
}

async function login () {
  try {
    const response = await axios.post('http://localhost:5000/login', {
      phone: phone.value,
      password: password.value
    });
    console.log('登录成功', response.data);
    store.setUser(response.data.user); // 确保这里的 user 数据是正确的
    store.setToken(response.data.token);
    router.push('/') // 登录成功后跳转到首页
  } catch (error) {
    console.error('登录失败:', error.response ? error.response.data.message : error.message);
  }
}

// 新增处理"加入校园"点击事件的方法
function handleJoinSchoolClick() {
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.warning('请先登录');
    router.push('/login');
  } else {
    goToChooseSchool.value = true;
  }
}

// 组件挂载时获取用户信息
onMounted(async () => {
  await fetchCurrentUser();
  console.log('组件挂载完成，用户是否有管理员角色:', hasAdminRole());
});

</script>

<style scoped>
::-webkit-scrollbar{
  display: none;
}
.top {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 60px;
  background-color: #121212;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 10;
  display: flex;
  align-items: center;
  /* padding: 0 20px; */
}

.left {
  width: 200px;
  display: flex;
  align-items: center;
}

.logo {
  width: 200px;
  height: 60px;
}

.center {
  flex-grow: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-menu {
  border: none !important;
  width: 100%;
  display: flex;
  justify-content: center;
}

.el-menu-item {
  font-size: 16px;
  font-weight: 500;
  padding: 0 20px !important;
  height: 60px;
  line-height: 60px;
  transition: all 0.3s ease;
}

/* .el-menu-item.is-active {
  background-color: #f9c32f;
  color: #d60630;
} */

.right {
  display: flex;
  align-items: center;
  background-color: transparent;
  padding-right: 20px;
}

.top-a {
  margin-left: 20px;
  padding: 8px 15px;
  background-color: #1f1b24;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.top-a:hover {
  background-color: #1e88e5;
  transform: translateY(-2px);
}

.user-info {
  display: flex;
  width: 100px;
  align-items: center;
  margin-left: 20px;
  position: relative;
  cursor: pointer;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.user-avatar:hover {
  transform: scale(1.05);
  border-color: #ffd04b;
}

.user-info span {
  margin: 0 10px;
  font-size: 14px;
  color: white;
  font-weight: 500;
}

.logout-button {
  position: absolute;
  bottom: -40px;
  left: 0;
  background-color: #ff4d4f;
  color: white;
  padding: 8px 15px;
  border-radius: 4px;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
  transform: translateY(10px);
}

.user-info:hover .logout-button {
  opacity: 1;
  visibility: visible;
  transform: translateY(0);
}

.logout-button:hover {
  background-color: #d43f3a;
}
</style>
